import api, ui, winGDI
from contentRecog import LinesWordsResult, recogUi, RecogImageInfo
from ctypes import windll
from .ocr import getOcrRecognizer
from . import bitmap
gdi32 = windll.gdi32
user32 = windll.user32
# 重写的 NVDA 识别结果类
class ImgRecogResultNVDAObject(recogUi.RecogResultNVDAObject):
    # 处理点击事件
    def script_activatePosition(self, gesture):pass
# 识别导航对象
def navigatorObjectScreenshot():
    # 获取导航对象
    nav = api.getNavigatorObject()
    try: # 得到导航对象的位置和大小
        left, top, width, height = nav.location
    except TypeError:
        ui.message(_("Content is not visible"))
        return
    # 生成图像信息
    imgInfo = RecogImageInfo(left, top, width, height, 1)
    # 从屏幕上抓取像素
    try:
        screenDC = user32.GetDC(0)
        memDC = gdi32.CreateCompatibleDC(screenDC)
        memBitmap = gdi32.CreateCompatibleBitmap(screenDC, imgInfo.recogWidth, imgInfo.recogHeight)
        oldBitmap = gdi32.SelectObject(memDC, memBitmap)
        gdi32.StretchBlt(memDC, 0, 0, width, height, screenDC, left, top, width, height, winGDI.SRCCOPY)
        # 把数据放入剪贴板
        bitmap.copyBitmapToClip(memBitmap)
    finally: # 清理现场
        gdi32.SelectObject(memDC, oldBitmap)
        gdi32.DeleteObject(memBitmap)
        gdi32.DeleteDC(memDC)
        user32.ReleaseDC(0, screenDC)
# 识别剪贴板图片
def recogClipBitmap():
    try:
        ocrRecognizer = getOcrRecognizer()
        imgInfo, data = bitmap.getClipImage()
        # 开始识别
        ret = ocrRecognizer.onRecog(data)
        # 生成 NVDA 约定的识别结果信息
        result = LinesWordsResult(ret, imgInfo)
        # 可以用光标浏览的识别结果文档对象
        obj = ImgRecogResultNVDAObject(result = result)
        obj.setFocus()
    except Exception as e:
        ui.message(_(f'{e}'))
